<?php

// 视频默认播放图片
define('DEFAULT_THUMB_URL', 'http://oss.mboxone.com/20170803/image/3/1501743459855242.jpg');
define('DEFAULT_TITLE', '点击查看视频');
define('DEFAULT_DESCRIPTION', "");

/**
 * 视频处理Module类
 * Class videoModule
 * 在做消息互动升级时加入
 * @author lilei<LL_strive@163.com> 2017-07-28
 */
class videoModule extends Module {

    public function run($message, $material, $userStatus) {
        $materialObj = simplexml_load_string($material->xml, 'SimpleXMLElement', LIBXML_NOCDATA);
//        $rm = $message->reply(message_type_image);
        $rm = new stdClass();
        $rm->content        = '';
        $rm->fromUserName   = $message->toUserName;
        $rm->toUserName     = $message->fromUserName;
        $rm->createTime     = time();
        $rm->msgType        = message_type_video;
        $rm->funcFlag       = 0;

        if ($material->media_id && strlen($material->media_id) > 100) {
            $media_ids = explode(',', (String)$material->media_id);
            $rm->media_id = $media_ids[0];
            $rm->thumb_media_id = $media_ids[1];
        } else {

            // 先看一下现在公众号后台素材的数量
            Module::callModule("messageSearch", null, "getMaterialCount", NULL);

            // 然后实例化咱们的素材数据表, 目的为了在素材内容上传后保存素材的media_id
            $materialModel = D("material");
            $id = $material->id;

            // 拿到xml数据里有用数据内容
            $materialObj = $materialObj->video->item;

            $videoUrl    = (String)$materialObj->videoUrl;
            $thumbUrl    = (String)$materialObj->thumbUrl;
            $title       = (String)$materialObj->title;
            $description = (String)$materialObj->description;
            $thumbUrl = (isset($thumbUrl) && !empty($thumbUrl)) ? $thumbUrl : DEFAULT_THUMB_URL;
            $title = (isset($title) && !empty($title)) ? $title : DEFAULT_TITLE;
            $description = (isset($description) && !empty($description)) ? $description : DEFAULT_DESCRIPTION;

            // 将资源从OSS下载到本地
            $result = self::saveFile($videoUrl, message_type_video);
            $result_thumb = self::saveFile($thumbUrl, message_type_image);

            $file_info = array(
                'filename' => $result['path'], // 资源相对于网站根目录的路径
                'content-type' => $result['content-type'], // 资源类型
                'filelength' => $result['size'] // 资源大小
            );
            $file_info['title']         = $title;
            $file_info['description']   = $description;
            $file_info_thumb = array(
                'filename' => $result_thumb['path'], // 资源相对于网站根目录的路径
                'content-type' => $result_thumb['content-type'], // 资源类型
                'filelength' => $result_thumb['size'] // 资源大小
            );

            $path = $result['path'];
            $path_thumb = $result_thumb['path'];

            // 资源上传微信素材库
            $result = WeixinApi::add_material("video", $file_info, $message->indMediaId);
            $result_thumb = WeixinApi::add_material("image", $file_info_thumb, $message->indMediaId);
            @unlink($path);     // 释放本地资源
            @unlink($path_thumb);     // 释放本地资源

            $result = json_decode($result, true);
            $result_thumb = json_decode($result_thumb, true);

            $media_id = $result['media_id'];
            $media_id_thumb = $result_thumb['media_id'];

            $data['media_id'] = $media_id . "," . $media_id_thumb;

//            $sql = "UPDATE `" . C(DB_PREFIX) . "material` SET `media_id` = '" . $media_id . "," . $media_id_thumb . "' where `id` = " . $id;
//            $exec_num = M()->execute($sql);
            $sql_result = $materialModel->where(['id' => $id])->save($data);

            $rm->media_id       = $media_id;
            $rm->thumb_media_id = $media_id_thumb;
            $rm->title          = $title;
            $rm->description    = $description;
        }

        if (!empty($material->accessTag) && !empty($message->fromUserName)) {
            setAccessTags($material->accessTag, $message->fromUserName, module_handle_text, $message->id);
        }
        return $rm;
    }

    /**
     * 将语音资源下载到本地
     *
     * @param $path     // OSS地址
     * @param $type     // 类型: image/video
     * @return mixed
     */
    public function saveFile($path, $type)
    {
        $fileName = pathinfo($path);
        $file_name = strToLower($fileName['basename']);

        $ch = curl_init($path);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
        $file = curl_exec($ch);
        curl_close($ch);

        $fp = fopen($file_name, 'w');
        fwrite($fp, $file);
        fclose($fp);

        if ($type == 'image' && filesize($file_name) >= 2048000) {
            self::resizejpg($file_name, 2000, $file_name);
        }

        $result['size'] = filesize($file_name);
        $result['path'] = $file_name;
        $result['content-type'] = $type . "/" . $fileName['extension'];
        return $result;
    }

    function resizejpg($imgsrc,$undersize,$savepath)
    {						//输出格式
        $arr = getimagesize($imgsrc);    						//获取源文件的长宽信息
        $size = filesize($imgsrc);
        $size = ceil($size/1024);       						//计算源文件的大小(kb)
        $percentum = $undersize / $size; 						//变成原来的多少
        if($size <= $undersize){								//已经满足的照片则不予处理
            return ;
        }
        $dest_area = $arr[0]*$arr[1]*$percentum;          		//转换之后的面积
        $newpercent = sqrt($dest_area/($arr[0]*$arr[1])); 		//长宽变化的比率
        $imgWidth = $arr[0]*$newpercent; 			       		//计算出来的宽缩放后的宽度
        $imgHeight = $arr[1]*$newpercent; 				  		//计算出来的高缩放后的高度

        // Create image and define colors
        $imgsrc = imagecreatefromjpeg($imgsrc);
        $image = imagecreatetruecolor($imgWidth, $imgHeight);   //创建一个彩色的底图
        imagecopyresampled($image, $imgsrc, 0, 0, 0, 0,$imgWidth,$imgHeight,$arr[0], $arr[1]);
        imagejpeg($image,$savepath);        				    //保存jpg格式图片
        imagedestroy($image);
    }


}

$module = new videoModule();
Module::addModule($module);